/**
* Author: fulishang
* Create Time  : 2016年8月4日,下午9:56:32
* Modify Time :
* Desc  : 
*/
package com.sam.si.file.processor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.messaging.Message;

import com.sam.si.file.util.Constants;

public class FileProcessor {
	private static final Logger LOGGER = Logger.getLogger(FileProcessor.class);
	private static final String HEADER_FILE_NAME = "file_name";

	public void process(Message<String> msg) {
		String fileName = (String) msg.getHeaders().get(HEADER_FILE_NAME);
		String content = msg.getPayload();
		File f = new File(Constants.TRANSFORMER_FILE_DIRECTORY);
		if (!f.exists()) {
			f.mkdirs();
		}
		//new file format should be yyyymmdd+origin name
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String newFileName = simpleDateFormat.format(new Date()) + fileName ;
		File newFile = new File(f, newFileName);
		if (!newFile.exists()) {
			try {
				newFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.writeStr2File(content, Constants.TRANSFORMER_FILE_DIRECTORY, newFileName);
		this.fileMove(Constants.ROUTER_FILE_DIRECTORY, Constants.ARCHIVED_FILE_DIRECTORY);
	}
	
	private void writeStr2File(String content, String path, String fileName) {
		
		try {
			FileOutputStream fos = new FileOutputStream(new File(path, fileName));
			Writer writer = new OutputStreamWriter(fos, "UTF-8");
			writer.write(content);
			writer.flush();
			writer.close();
			LOGGER.info("data copy done for new file....");
		} catch (Exception e) {
			LOGGER.error("FAIL to write string to new file...");
		}
		
	}
	
	private void fileMove(String from, String to) {
		
		File dir = new File(from);
		File[] files = dir.listFiles();
		if (files == null) {
			LOGGER.info("Nothing to archived...");
			return;
		}			
		File toDir = new File(to);
		if (!toDir.exists()) {
			toDir.mkdirs();
		}
		for (int i=0; i<files.length; i++) {
			LOGGER.info("Arching the file -- " + files[i]);
			if (files[i].isDirectory()) { //iter the folder
				fileMove(files[i].getPath(), to + "/" + files[i].getName());
				files[i].delete();
			}
			File moveFile = new File(toDir.getPath()+"/"+files[i].getName());
			if (moveFile.exists()) {
				moveFile.delete();
			}
			files[i].renameTo(moveFile);
			LOGGER.info("Archive file successfully....");
		}
		
		
		
	}
	
	

}
